<template>
  <div>
    <el-upload
      :action="uploadUrl"
      :data="fromdata"
      :multiple=true
      list-type="picture-card"
      :before-upload="handleBeforeUpload"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      accept="image/*"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" style="width: 100%;height: 100%;text-align: center" :title="图片预览">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
  export default {
    props: {
      description: {
        type: String,
        default: ""
      },
      uploadUrl: {
        type: String,
        default: "http://7326.oss-cn-beijing.aliyuncs.com"
      },
      policyUrl: {
        type: String,
        default: '/file/get/policy'
      },
      success_action_status: {
        type: Number,
        default: 200
      },
    },
    data() {
      return {
        dialogImageUrl: "",
        dialogVisible: false,
        files: [],
        fromdata: {
          success_action_status: this.success_action_status,
          description: this.description,
          keyDir: "",
          key: "",
          OSSAccessKeyId: "",
          policy: "",
          Signature: "",
          expire: ""
        }
      }
    },
    methods: {
      handleBeforeUpload(file) {
        this.fromdata.key = this.fromdata.keyDir + this.guid() + file.name;
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handleSuccess(response, file, fileList) {
        console.log("成功");
        console.log(file);
        console.log(fileList);
        this.files.push({
          fileName:this.fromdata.description,
          fileUrl:this.fromdata.key,
        });
        this.$emit('onUploadSuccess',this.files);
      },
      guid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
          return v.toString(16);
        });
      }

    },
    mounted() {
      //获取文件上传签名
      this.$http({
        url: this.$http.adornUrl(this.policyUrl),
        method: 'get'
      }).then(({data}) => {
        this.fromdata.OSSAccessKeyId = data.accessid;
        this.fromdata.policy = data.policy;
        this.fromdata.Signature = data.signature;
        this.fromdata.expire = data.expire;
        this.fromdata.keyDir = data.dir;
      })
    }
  }
</script>

<style scoped>

</style>
